define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'echarts', 'bootstrap-datetimepicker'], function ($, undefined, Backend, Table, Form, echarts) {

    var Controller = {
        index: function () {
            // 初始化表格参数
            Table.api.init({
                extend: {
                    index_url: 'scanwork/quality_record/index' + location.search,
                    detail_url: 'scanwork/quality_record/detail',
                    del_url: 'scanwork/quality_record/del',
                    multi_url: 'scanwork/quality_record/multi',
                    import_url: 'scanwork/quality_record/import',
                    table: 'quality_record',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'report.allocation.plan.plan_code', title: '小工单计划编码', operate: 'LIKE'},
                        {field: 'report.allocation.order.order_name', title: '订单名称', operate: 'LIKE'},
                        {field: 'report.allocation.process.name', title: '工序', operate: 'LIKE'},
                        {field: 'report.allocation.model.name', title: '产品型号', operate: 'LIKE'},
                        {field: 'report.quantity', title: '报工数量'},
                        {field: 'report.user.nickname', title: '报工员', operate: 'LIKE'},
                        {field: 'overall_result', title: '质检结果', searchList: {"1":"合格","2":"不合格","3":"让步接收"}, formatter: function(value, row, index) {
                            var resultList = {"1":"合格","2":"不合格","3":"让步接收"};
                            var colorList = {"1":"success","2":"danger","3":"warning"};
                            return '<span class="label label-' + colorList[value] + '">' + resultList[value] + '</span>';
                        }},
                        {field: 'handle_method', title: '处理方式', searchList: {"1":"返工","2":"报废","3":"让步接收"}, formatter: function(value, row, index) {
                            var methodList = {"1":"返工","2":"报废","3":"让步接收"};
                            return methodList[value] || '--';
                        }},
                        {field: 'check_time', title: '检验时间', operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: function(value, row, index) {
                            var table = this.table;
                            var options = table.bootstrapTable('getOptions');
                            var buttons = [];
                            buttons.push('<a class="btn btn-success btn-xs btn-changeit" href="' + Fast.api.fixurl('scanwork/quality_record/detail?ids=' + row.id) + '" title="查看详情"><i class="fa fa-eye"></i></a>');
                            return buttons.join(' ');
                        }}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        pending: function () {
            // 初始化表格参数
            Table.api.init({
                extend: {
                    index_url: 'scanwork/quality_record/pending' + location.search,
                    execute_url: 'scanwork/quality_record/execute',
                    table: 'scanwork_report',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'allocation.plan.plan_code', title: '小工单计划编码', operate: 'LIKE'},
                        {field: 'allocation.order.order_name', title: '订单名称', operate: 'LIKE'},
                        {field: 'allocation.process.name', title: '工序', operate: 'LIKE'},
                        {field: 'allocation.model.name', title: '产品型号', operate: 'LIKE'},
                        {field: 'quantity', title: '报工数量'},
                        {field: 'user.nickname', title: '报工员', operate: 'LIKE'},
                        {field: 'createtime', title: '报工时间', operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: function(value, row, index) {
                            var table = this.table;
                            var options = table.bootstrapTable('getOptions');
                            var buttons = [];
                            buttons.push('<a class="btn btn-primary btn-xs btn-changeit" href="' + Fast.api.fixurl('scanwork/quality_record/execute?id=' + row.id) + '" title="执行质检"><i class="fa fa-check"></i></a>');
                            return buttons.join(' ');
                        }}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        execute: function () {
            Controller.api.bindevent();
            Controller.api.initExecuteForm();
        },
        detail: function () {
            Controller.api.bindevent();
            Controller.api.initDetailPage();
        },
        statistics: function () {
            Controller.api.initStatisticsPage();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            initExecuteForm: function() {
                // 从隐藏的div元素中获取质检标准数据
                var checkItemsData = {};
                var dataElement = document.getElementById('check-items-data');
                if (dataElement && dataElement.textContent) {
                    try {
                        checkItemsData = JSON.parse(dataElement.textContent);
                    } catch (e) {
                        console.error('解析检查项目数据失败:', e);
                    }
                }
                
                // 生成检查项目表单
                Controller.api.generateCheckItemsForm(checkItemsData);
                
                // 表单提交
                $('#execute-form').on('submit', function(e) {
                    e.preventDefault();
                    
                    var formData = {
                        'row[check_results]': Controller.api.collectCheckResults(),
                        'row[handle_method]': $('#c-handle_method').val(),
                        'row[remark]': $('#c-remark').val()
                    };
                    
                    $.post('', formData, function(data) {
                        if (data.code == 1) {
                            Toastr.success(data.msg);
                            setTimeout(function() {
                                window.location.href = Fast.api.fixurl('scanwork/quality_record/pending');
                            }, 1500);
                        } else {
                            Toastr.error(data.msg);
                        }
                    });
                });
            },
            generateCheckItemsForm: function(standardData) {
                var container = $('#check-items-container');
                var html = '';
                
                for (var category in standardData) {
                    html += '<div class="panel panel-default">';
                    html += '<div class="panel-heading"><h5 class="panel-title">' + category + '</h5></div>';
                    html += '<div class="panel-body">';
                    
                    for (var item in standardData[category]) {
                        var options = standardData[category][item].split('/');
                        html += '<div class="form-group">';
                        html += '<label class="control-label col-sm-3">' + item + ':</label>';
                        html += '<div class="col-sm-9">';
                        
                        for (var i = 0; i < options.length; i++) {
                            var option = options[i];
                            var checked = (i === 0) ? 'checked' : '';
                            html += '<label class="radio-inline">';
                            html += '<input type="radio" name="check_results[' + category + '][' + item + ']" value="' + option + '" ' + checked + '> ' + option;
                            html += '</label>';
                        }
                        
                        html += '</div></div>';
                    }
                    
                    html += '</div></div>';
                }
                
                container.html(html);
            },
            collectCheckResults: function() {
                var results = {};
                
                $('input[name^="check_results"]').each(function() {
                    var name = $(this).attr('name');
                    var value = $(this).val();
                    
                    // 解析name属性获取分类和项目
                    var matches = name.match(/check_results\[([^\]]+)\]\[([^\]]+)\]/);
                    if (matches) {
                        var category = matches[1];
                        var item = matches[2];
                        
                        if (!results[category]) {
                            results[category] = {};
                        }
                        
                        if ($(this).is(':checked')) {
                            results[category][item] = value;
                        }
                    }
                });
                
                return results;
            },
            getUrlParam: function(name) {
                var urlParams = new URLSearchParams(window.location.search);
                return urlParams.get(name);
            },
            initDetailPage: function() {
                // 获取检查结果数据
                var container = $('#check-results-container');
                if (container.length > 0) {
                    var checkResultsStr = container.attr('data-results');
                    console.log('检查结果原始数据:', checkResultsStr);
                    
                    try {
                        var checkResults = checkResultsStr ? JSON.parse(checkResultsStr) : {};
                        console.log('解析后的检查结果:', checkResults);
                        
                        // 生成检查结果展示
                        Controller.api.generateCheckResultsDisplay(checkResults);
                    } catch (e) {
                        console.error('解析检查结果数据失败:', e);
                        container.html('<p class="text-danger">检查结果数据格式错误</p>');
                    }
                }
            },
            generateCheckResultsDisplay: function(checkResults) {
                var container = $('#check-results-container');
                var html = '';
                
                if (!checkResults || Object.keys(checkResults).length === 0) {
                    container.html('<p class="text-muted">暂无检查结果数据</p>');
                    return;
                }
                
                for (var category in checkResults) {
                    if (checkResults.hasOwnProperty(category)) {
                        html += '<div class="panel panel-default">';
                        html += '<div class="panel-heading"><h5 class="panel-title"><strong>' + category + '</strong></h5></div>';
                        html += '<div class="panel-body">';
                        html += '<div class="row">';
                        
                        var itemCount = 0;
                        for (var item in checkResults[category]) {
                            if (checkResults[category].hasOwnProperty(item)) {
                                var result = checkResults[category][item];
                                var labelClass = Controller.api.getResultLabelClass(result);
                                
                                html += '<div class="col-md-4 col-sm-6">';
                                html += '<div class="form-group">';
                                html += '<label class="control-label">' + item + ':</label> ';
                                html += '<span class="label ' + labelClass + '" style="margin-left: 10px;">' + result + '</span>';
                                html += '</div>';
                                html += '</div>';
                                
                                itemCount++;
                            }
                        }
                        
                        html += '</div>'; // close row
                        html += '</div>'; // close panel-body
                        html += '</div>'; // close panel
                    }
                }
                
                container.html(html);
            },
            getResultLabelClass: function(result) {
                if (result === '合格' || result === '无' || result === '无缺陷' || result === '无毛刺' || result === '无划痕' || result === '无变形') {
                    return 'label-success';
                } else if (result === '不合格' || result === '有缺陷' || result === '有毛刺' || result === '有划痕' || result === '有变形') {
                    return 'label-danger';
                } else {
                    return 'label-default';
                }
            },
            // 统计页面初始化
            initStatisticsPage: function() {
                // 初始化日期选择器
                $('.datetimepicker').datetimepicker({
                    format: 'YYYY-MM-DD',
                    locale: 'zh-cn'
                });
                
                // 初始化图表容器
                Controller.api.trendChart = echarts.init(document.getElementById('trend-chart'));
                Controller.api.resultPieChart = echarts.init(document.getElementById('result-pie-chart'));
                Controller.api.processChart = echarts.init(document.getElementById('process-chart'));
                Controller.api.defectChart = echarts.init(document.getElementById('defect-chart'));
                
                console.log('图表初始化完成');
                
                // 绑定查询按钮
                $('#btn-search').on('click', function() {
                    Controller.api.loadStatisticsData();
                });
                
                // 绑定导出按钮
                $('#btn-export').on('click', function() {
                    Controller.api.exportReport();
                });
                
                // 加载初始数据
                console.log('开始加载统计数据...');
                Controller.api.loadStatisticsData();
            },
            // 加载统计数据
            loadStatisticsData: function() {
                var startDate = $('#start-date').val();
                var endDate = $('#end-date').val();
                
                // 加载总体统计
                Controller.api.loadOverviewData(startDate, endDate);
                // 加载趋势数据
                Controller.api.loadTrendData(startDate, endDate);
                // 加载工序统计
                Controller.api.loadProcessData(startDate, endDate);
                // 加载不合格项统计
                Controller.api.loadDefectData(startDate, endDate);
            },
            // 加载总体统计数据
            loadOverviewData: function(startDate, endDate) {
                $.ajax({
                    url: Fast.api.fixurl('scanwork/quality_record/statistics'),
                    type: 'GET',
                    data: {
                        type: 'overview',
                        start_date: startDate,
                        end_date: endDate
                    },
                    success: function(res) {
                        console.log('总体统计数据:', res);
                        if (res.code === 1) {
                            var data = res.data;
                            $('#stat-total').text(data.total);
                            $('#stat-qualified').text(data.qualified);
                            $('#stat-unqualified').text(data.unqualified);
                            $('#stat-rate').text(data.qualified_rate + '%');
                            
                            // 更新饼图
                            Controller.api.updateResultPieChart(data);
                        } else {
                            console.error('获取总体统计失败:', res.msg || res);
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('请求失败:', status, error);
                        Toastr.error('加载统计数据失败，请查看控制台');
                    }
                });
            },
            // 加载趋势数据
            loadTrendData: function(startDate, endDate) {
                $.ajax({
                    url: Fast.api.fixurl('scanwork/quality_record/statistics'),
                    type: 'GET',
                    data: {
                        type: 'trend',
                        days: 30
                    },
                    success: function(res) {
                        if (res.code === 1) {
                            Controller.api.updateTrendChart(res.data);
                        }
                    }
                });
            },
            // 加载工序统计数据
            loadProcessData: function(startDate, endDate) {
                $.ajax({
                    url: Fast.api.fixurl('scanwork/quality_record/statistics'),
                    type: 'GET',
                    data: {
                        type: 'process',
                        start_date: startDate,
                        end_date: endDate
                    },
                    success: function(res) {
                        if (res.code === 1) {
                            Controller.api.updateProcessChart(res.data);
                        }
                    }
                });
            },
            // 加载不合格项统计
            loadDefectData: function(startDate, endDate) {
                $.ajax({
                    url: Fast.api.fixurl('scanwork/quality_record/statistics'),
                    type: 'GET',
                    data: {
                        type: 'defect',
                        start_date: startDate,
                        end_date: endDate
                    },
                    success: function(res) {
                        if (res.code === 1) {
                            Controller.api.updateDefectChart(res.data);
                        }
                    }
                });
            },
            // 更新趋势图
            updateTrendChart: function(data) {
                var option = {
                    title: {
                        text: '近30天质检趋势'
                    },
                    tooltip: {
                        trigger: 'axis'
                    },
                    legend: {
                        data: ['合格', '不合格']
                    },
                    xAxis: {
                        type: 'category',
                        data: data.dates,
                        axisLabel: {
                            rotate: 45
                        }
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            name: '合格',
                            type: 'line',
                            data: data.qualified,
                            itemStyle: {color: '#5cb85c'},
                            smooth: true
                        },
                        {
                            name: '不合格',
                            type: 'line',
                            data: data.unqualified,
                            itemStyle: {color: '#d9534f'},
                            smooth: true
                        }
                    ]
                };
                Controller.api.trendChart.setOption(option);
            },
            // 更新结果饼图
            updateResultPieChart: function(data) {
                var option = {
                    title: {
                        text: '质检结果分布',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left'
                    },
                    series: [
                        {
                            name: '质检结果',
                            type: 'pie',
                            radius: '50%',
                            data: [
                                {value: data.qualified, name: '合格', itemStyle: {color: '#5cb85c'}},
                                {value: data.unqualified, name: '不合格', itemStyle: {color: '#d9534f'}},
                                {value: data.concession, name: '让步接收', itemStyle: {color: '#f0ad4e'}}
                            ],
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                };
                Controller.api.resultPieChart.setOption(option);
            },
            // 更新工序图表
            updateProcessChart: function(data) {
                var processNames = [];
                var qualifiedData = [];
                var unqualifiedData = [];
                
                data.forEach(function(item) {
                    processNames.push(item.process_name || '未知工序');
                    qualifiedData.push(item.qualified);
                    unqualifiedData.push(item.unqualified);
                });
                
                var option = {
                    title: {
                        text: '工序质检统计'
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    legend: {
                        data: ['合格', '不合格']
                    },
                    xAxis: {
                        type: 'value'
                    },
                    yAxis: {
                        type: 'category',
                        data: processNames
                    },
                    series: [
                        {
                            name: '合格',
                            type: 'bar',
                            stack: 'total',
                            data: qualifiedData,
                            itemStyle: {color: '#5cb85c'}
                        },
                        {
                            name: '不合格',
                            type: 'bar',
                            stack: 'total',
                            data: unqualifiedData,
                            itemStyle: {color: '#d9534f'}
                        }
                    ]
                };
                Controller.api.processChart.setOption(option);
            },
            // 更新不合格项图表
            updateDefectChart: function(data) {
                var option = {
                    title: {
                        text: '不合格项TOP10'
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    xAxis: {
                        type: 'category',
                        data: data.items,
                        axisLabel: {
                            rotate: 45,
                            interval: 0
                        }
                    },
                    yAxis: {
                        type: 'value'
                    },
                    series: [
                        {
                            name: '出现次数',
                            type: 'bar',
                            data: data.counts,
                            itemStyle: {color: '#d9534f'}
                        }
                    ]
                };
                Controller.api.defectChart.setOption(option);
            },
            // 导出报表
            exportReport: function() {
                var startDate = $('#start-date').val();
                var endDate = $('#end-date').val();
                
                window.location.href = Fast.api.fixurl('scanwork/quality_record/export') + 
                    '?start_date=' + startDate + '&end_date=' + endDate;
            }
        }
    };
    return Controller;
});